package com.tang.window;

import com.tang.bean.WaterSensor;
import com.tang.functions.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * 增量聚合与全量聚合联合使用
 *
 * @author tang
 * @since 2023/6/11 12:25
 */
public class WindowAggregateAndProcessDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> source = env
                .socketTextStream("192.168.70.141", 7777)
                .map(new WaterSensorMapFunction());

        KeyedStream<WaterSensor, String> keyedStream = source.keyBy(WaterSensor::getId);

        // 1。窗口分配器
        WindowedStream<WaterSensor, String, TimeWindow> window = keyedStream
                .window(TumblingProcessingTimeWindows.of(Time.seconds(20)));
        // 2. 窗口函数：增量聚合 Aggregate
        /*
         * 1、属于本窗口的第一条数据来，创建窗口，创建累加器
         * 2、增量聚合： 来一条计算一条， 调用一次add方法
         * 3、窗口输出时调用一次getresult方法
         * 4、输入、中间累加器、输出 类型可以不一样，非常灵活
         */
        SingleOutputStreamOperator<String> aggregate = window.aggregate(
                new MyAgg(), new MyProcess());

        aggregate.print();

        env.execute();

    }


    public static class MyAgg implements AggregateFunction<WaterSensor, Integer, String> {

        /**
         * 创建累加器，给定累加器的初始值
         * @return 累加器初始值
         */
        @Override
        public Integer createAccumulator() {
            System.out.println("创建累加器");
            return 0;
        }

        /**
         * 聚合逻辑
         *
         * @param value The value to add
         * @param accumulator The accumulator to add the value to
         * @return 累加后的值
         */
        @Override
        public Integer add(WaterSensor value, Integer accumulator) {
            System.out.println("调用add方法,value=" + value);
            return accumulator + value.getVc();
        }

        /**
         * 窗口结束时调用的结果输出
         *
         * @param accumulator The accumulator of the aggregation
         * @return 输出的结果
         */
        @Override
        public String getResult(Integer accumulator) {
            System.out.println("调用getResult方法");
            return accumulator.toString();
        }

        @Override
        public Integer merge(Integer a, Integer b) {
            // 只有会话窗口才会用到
            System.out.println("调用merge方法");
            return null;
        }
    }

    /**
     * in,out,key
     */
    public static class MyProcess extends ProcessWindowFunction<String, String, String, TimeWindow> {

        /**
         * 
         * @param s key
         * @param context  上下文
         * @param elements 数据
         * @param out 输出
         * @throws Exception -
         */
        @Override
        public void process(String s, ProcessWindowFunction<String, String, String, TimeWindow>.Context context, Iterable<String> elements, Collector<String> out) throws Exception {
            long start = context.window().getStart();
            long end = context.window().getEnd();
            String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
            String windowStart = DateFormatUtils.format(start, pattern);
            String windowEnd = DateFormatUtils.format(end, pattern);

            long count = elements.spliterator().estimateSize();
            out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含"
                    + count + "条数据====>" + elements);
        }
    }
    
}